import { Input, DatePicker } from 'antd';
import type { FC } from 'react';
import { useEffect, useState } from 'react';
import styles from './index.less';
type ValueType = {
  price?: string | number;
  date?: string;
};
interface Props {
  value?: ValueType;
  onChange?: (value: ValueType) => void;
  inputPlaceholder?: string;
}
const Index: FC<Props> = ({ onChange, value, inputPlaceholder = '请填写' }) => {
  const [val, setVal] = useState<ValueType>({
    price: undefined,
    date: undefined,
  });
  const update = (value) => {
    if (onChange) {
      onChange?.(value);
    } else {
      setVal(value);
    }
  };
  const onPriceChange = (evt) => {
    update({
      ...val,
      price: evt.target.value?.replace(/^(0+)|[^\d]+/g, ''),
    });
  };
  const onDateChange = (date) => {
    update({
      ...val,
      date,
    });
  };
  useEffect(() => {
    if (value) {
      setVal(value);
    } else {
      setVal({
        price: undefined,
        date: undefined,
      });
    }
  }, [value]);
  return (
    <div className={styles.container}>
      <Input
        value={val.price}
        onChange={onPriceChange}
        className={styles.first}
        placeholder={inputPlaceholder}
        addonAfter="¥"
        type="number"
      />
      <DatePicker
        value={val.date}
        onChange={onDateChange}
        placeholder="设置到期日期"
        style={{ width: 220 }}
      />
    </div>
  );
};

export default Index;
